import React from 'react';
import ReactMarkdown from 'react-markdown';
import RemarkGfm from 'remark-gfm';
import RehypeKatex from 'rehype-katex'
import RemarkBreaks from 'remark-breaks';
import RehypeRaw from 'rehype-raw'
import RemarkMath from 'remark-math';
import SyntaxHighlighter from 'react-syntax-highlighter'
import { atelierHeathLight } from 'react-syntax-highlighter/dist/esm/styles/hljs'

const getCorrectCapitalizationLanguageName = (language) => {
  if (!language)
    return 'Plain'

  // if (language in capitalizationLanguageNameMap)
  //   return capitalizationLanguageNameMap[language]

  return language.charAt(0).toUpperCase() + language.substring(1)
}

const CodeBlock = ({ inline, className, children, ...props }) => {
  const match = /language-(\w+)/.exec(className || '');
  const language = match?.[1];
  const languageShowName = getCorrectCapitalizationLanguageName(language || '');
  const content = String(children).replace(/\n$/, '');

  if (inline || !match)
    return <code {...props} className={className}>{children}</code>

  return (
    <div>
      <SyntaxHighlighter
        {...props}
        style={atelierHeathLight}
        customStyle={{
          paddingLeft: 12,
          backgroundColor: '#fff',
        }}
        language={match?.[1]}
        showLineNumbers
        PreTag="div"
      >
        {content}
      </SyntaxHighlighter>
    </div>
  )
}

const Paragraph = (paragraph) => {
  const { node } = paragraph
  const children_node = node.children
  if (children_node && children_node[0] && 'tagName' in children_node[0] && children_node[0].tagName === 'img') {
    return (
      <>
        {/* <ImageGallery srcs={[children_node[0].properties.src]} /> */}
        <p>{paragraph.children.slice(1)}</p>
      </>
    )
  }
  return <p>{paragraph.children}</p>
}

const preprocessLaTeX = (content) => {
  if (typeof content !== 'string')
    return content
  return content.replace(/\\\[(.*?)\\\]/g, (_, equation) => `$$${equation}$$`)
    .replace(/\\\((.*?)\\\)/g, (_, equation) => `$$${equation}$$`)
    .replace(/(^|[^\\])\$(.+?)\$/g, (_, prefix, equation) => `${prefix}$${equation}$`)
}

function Markdown(props) {
  const latexContent = preprocessLaTeX(props.content)
  return (
    <ReactMarkdown
      remarkPlugins={[RemarkGfm, RemarkMath, RemarkBreaks]}
      rehypePlugins={[
        RehypeKatex,
        RehypeRaw,
        // The Rehype plug-in is used to remove the ref attribute of an element
        () => {
          return (tree) => {
            const iterate = (node) => {
              if (node.type === 'element' && !node.properties?.src && node.properties?.ref && node.properties.ref.startsWith('{') && node.properties.ref.endsWith('}'))
                delete node.properties.ref

              if (node.children)
                node.children.forEach(iterate)
            }
            tree.children.forEach(iterate)
          }
        },
      ]}
      disallowedElements={['iframe', 'head', 'html', 'meta', 'link', 'style', 'body']}
      components={{
        code: CodeBlock,
        // img: Img,
        // video: VideoBlock,
        // audio: AudioBlock,
        // a: Link,
        // p: Paragraph,
        // button: MarkdownButton,
        // form: MarkdownForm,
        // script: ScriptBlock,
      }}
      // linkTarget='_blank'
    >
      {/* Markdown detect has problem. */}
      {latexContent}
    </ReactMarkdown>
  );
}

export default Markdown;